<template>
  <div class="battle">
    <!-- Battle arena -->
    <div class="battle-arena" v-if="isBattleReady">
      <!-- Opponent area -->
      <div class="opponent-area">
        <div class="pokemon-info">
          <div>
            <p class="pokemon-level">Lv. {{ currentOpponent?.level }}</p>
            <h2 class="pokemon-name">{{ currentOpponent?.name || 'Unknown' }}</h2>
            <div class="hp-bar-container">
              <div class="hp-bar">
                <div
                    class="hp-fill"
                    :class="{ 'low-hp': currentOpponent?.currentHp / currentOpponent?.hp < 0.3 }"
                    :style="{ width: currentOpponent ? `${(currentOpponent.currentHp / currentOpponent.hp) * 100}%` : '0%' }"
                ></div>
              </div>
              <span class="hp-text">{{ currentOpponent?.currentHp ?? 0 }}/{{ currentOpponent?.hp ?? 0 }}</span>
            </div>
          </div>
          <div class="pokemon-sprite-container">
            <div class="sprite-shadow"></div>
            <img
                v-if="currentOpponent"
                :src="`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${currentOpponent.id}.png`"
                :alt="currentOpponent.name"
                class="pokemon-sprite opponent-sprite"
            />
          </div>
        </div>
      </div>



      <!-- Player area -->
      <div class="player-area">
        <div class="pokemon-info">
          <div class="pokemon-sprite-container">
            <div class="sprite-shadow"></div>
            <img
                v-if="currentPlayer"
                :src="`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/${currentPlayer.id}.png`"
                :alt="currentPlayer.name"
                class="pokemon-sprite player-sprite"
            />
          </div>
          <div class="player-stats">
            <p class="pokemon-level">Lv. {{ currentPlayer?.level }}</p>
            <h2 class="pokemon-name">{{ currentPlayer?.name || 'Unknown' }}</h2>
            <div class="hp-bar-container reverse">
              <span class="hp-text">{{ currentPlayer?.currentHp ?? 0 }}/{{ currentPlayer?.hp ?? 0 }}</span>
              <div class="hp-bar">
                <div
                    class="hp-fill"
                    :class="{ 'low-hp': currentPlayer?.currentHp/currentPlayer?.hp < 0.3 }"
                    :style="{ width: currentPlayer ? `${(currentPlayer.currentHp / currentPlayer.hp) * 100}%` : '0%' }"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>


      <!-- bottom -->
      <div style="display: flex">
        <!-- Battle log -->
        <div class="battle-log-container">
          <div class="battle-log">
            <p v-for="(log, index) in battleLog" :key="index" class="log-entry">
              {{ log }}
            </p>
          </div>
        </div>



        <!-- Battle controls -->
        <div class="battle-controls">
          <!-- Battle Result -->
          <div v-if="battleState !== 'active'" class="battle-result">
            <p class="result-text">
              {{ battleState === 'victory' ? 'You won the battle!' : battleState === 'caught' ? 'Pokémon caught!' : 'You lost the battle!' }}
            </p>
            <button class="return-button" @click="endBattle">End Battle</button>
          </div>

          <!-- Main Controls -->
          <div v-else-if="controlState === 'main'" class="controls-container">
            <div class="main-controls-grid">
              <button
                  class="control-button fight-button"
                  @click="controlState = 'fight'"
                  :disabled="turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked"
                  :class="{ disabled: turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked }"
              >
                战斗
              </button>
              <button
                  class="control-button item-button"
                  @click="controlState = 'item'"
                  :disabled="turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked"
                  :class="{ disabled: turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked }"
              >
                道具
              </button>
              <button
                  class="control-button switch-button"
                  @click="controlState = 'switch'"
                  :disabled="turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked"
                  :class="{ disabled: turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked }"
              >
                切换
              </button>
              <button
                  class="control-button run-button"
                  @click="runAway"
                  :disabled="turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked"
                  :class="{ disabled: turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked }"
              >
                撤退
              </button>
            </div>
          </div>

          <!-- Fight Controls -->
          <div v-else-if="controlState === 'fight'" class="controls-container">
            <div class="moves-grid">
              <button
                  v-for="(move, index) in currentPlayer?.moves || []"
                  :key="index"
                  @click="handleAttack(index)"
                  :disabled="turn !== 'player' || !currentPlayer || move.pp <= 0 || battleState !== 'active' || isTurnTransitioning || isActionLocked"
                  :class="['move-button', turn !== 'player' || move.pp <= 0 || battleState !== 'active' || isTurnTransitioning || isActionLocked ? 'disabled' : '']"
                  :style="{ backgroundColor: move ? getTypeColor(move.type) : '#9e9e9e' }"
              >
                <div class="move-content">
                  <span class="move-name">{{ move?.name || 'Unknown' }}</span>
                  <span class="type-badge">{{ move?.type || 'Unknown' }}</span>
                  <span class="pp-text">{{ move?.pp ?? 0 }}/{{ move?.maxPp ?? 25 }}</span>
                </div>
              </button>
            </div>
            <button
                class="back-button"
                @click="controlState = 'main'"
                :disabled="turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked"
                :class="{ disabled: turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked }"
            >
              Back
            </button>
          </div>

          <!-- Item Controls -->
          <div v-else-if="controlState === 'item'" class="controls-container">
            <div class="items-grid">
              <button
                  class="item-button"
                  @click="usePokeBall"
                  :disabled="items.pokeBall <= 0 || turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked"
                  :class="{ disabled: items.pokeBall <= 0 || turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked }"
              >
                Poké Ball ({{ items.pokeBall }})
              </button>
              <button
                  class="item-button"
                  @click="usePotion"
                  :disabled="items.potion <= 0 || turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked"
                  :class="{ disabled: items.potion <= 0 || turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked }"
              >
                Potion ({{ items.potion }})
              </button>
            </div>
            <button
                class="back-button"
                @click="controlState = 'main'"
                :disabled="turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked"
                :class="{ disabled: turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked }"
            >
              Back
            </button>
          </div>

          <!-- Switch Controls -->
          <div v-else-if="controlState === 'switch'" class="controls-container">
            <div class="pokemon-switch-grid">
              <div
                  v-for="(pokemon, index) in props.playerPokemon"
                  :key="pokemon.id"
                  class="pokemon-card"
                  @click="switchPokemon(index)"
                  :class="{ disabled: pokemon.currentHp <= 0 || turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked }"
              >
                <div class="pokemon-card-content">
                  <img
                      :src="`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemon.id}.png`"
                      :alt="pokemon.name"
                      class="pokemon-thumbnail"
                  />
                  <h3 class="pokemon-card-name">{{ pokemon.name }}</h3>
                  <p class="pokemon-level">Lv. {{ pokemon.level }}</p>
                  <div class="hp-bar-container">
                    <div class="hp-bar">
                      <div
                          class="hp-fill"
                          :class="{ 'low-hp': pokemon.currentHp < 30 }"
                          :style="{ width: `${(pokemon.currentHp / pokemon.hp) * 100}%` }"
                      ></div>
                    </div>
                    <span class="hp-text">{{ pokemon.currentHp }}/{{ pokemon.hp }}</span>
                  </div>
                </div>
              </div>
            </div>
            <button
                class="back-button"
                @click="controlState = 'main'"
                :disabled="turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked"
                :class="{ disabled: turn !== 'player' || battleState !== 'active' || isTurnTransitioning || isActionLocked }"
            >
              Back
            </button>
          </div>
        </div>


      </div>


    </div>
    <div v-else class="loading">Loading battle data...</div>
  </div>
</template>

<script setup>
import { ref, onMounted, inject, watch, nextTick } from 'vue';
import { typeColorMap } from '@/api/constants';

const props = defineProps({
  playerPokemon: {
    type: Array,
    required: true,
    default: () => []
  },
  opponentPokemon: {
    type: Array,
    required: true,
    default: () => []
  }
});

const emit = defineEmits(['battleEnd']);
const myPokemon = inject('myPokemon');
const items = inject('items');

const battleLog = ref([]);
const turn = ref('player');
const battleState = ref('active');
const controlState = ref('main'); // 'main', 'fight', 'item', 'switch'
const currentPlayerIndex = ref(0);
const currentOpponentIndex = ref(0);
const currentPlayer = ref(null);
const currentOpponent = ref(null);
const isBattleReady = ref(false);
const isTurnTransitioning = ref(false);
const isActionLocked = ref(false); // New: Locks actions after one is taken

// Type effectiveness chart
const typeChart = {
  一般: { 格斗: 2, 幽灵: 0 },
  火: { 草: 2, 虫: 2, 冰: 2, 钢: 2, 水: 0.5, 火: 0.5, 岩石: 0.5, 龙: 0.5 },
  水: { 火: 2, 地面: 2, 岩石: 2, 水: 0.5, 草: 0.5, 龙: 0.5 },
  草: { 水: 2, 地面: 2, 岩石: 2, 火: 0.5, 草: 0.5, 毒: 0.5, 飞行: 0.5, 虫: 0.5, 龙: 0.5, 钢: 0.5 },
  电: { 水: 2, 飞行: 2, 电: 0.5, 草: 0.5, 地面: 0, 龙: 0.5 },
  冰: { 草: 2, 地面: 2, 飞行: 2, 龙: 2, 水: 0.5, 火: 0.5, 冰: 0.5, 钢: 0.5 },
  格斗: { 一般: 2, 冰: 2, 岩石: 2, 恶: 2, 钢: 2, 毒: 0.5, 飞行: 0.5, 超能力: 0.5, 虫: 0.5, 妖精: 0.5, 幽灵: 0 },
  毒: { 草: 2, 妖精: 2, 毒: 0.5, 地面: 0.5, 岩石: 0.5, 幽灵: 0.5, 钢: 0 },
  地面: { 火: 2, 电: 2, 毒: 2, 岩石: 2, 钢: 2, 草: 0.5, 虫: 0.5, 飞行: 0 },
  飞行: { 草: 2, 格斗: 2, 虫: 2, 电: 0.5, 岩石: 0.5, 钢: 0.5 },
  超能力: { 格斗: 2, 毒: 2, 超能力: 0.5, 钢: 0.5, 恶: 0 },
  虫: { 草: 2, 超能力: 2, 恶: 2, 火: 0.5, 格斗: 0.5, 毒: 0.5, 飞行: 0.5, 幽灵: 0.5, 钢: 0.5, 妖精: 0.5 },
  岩石: { 火: 2, 冰: 2, 飞行: 2, 虫: 2, 格斗: 0.5, 地面: 0.5, 钢: 0.5 },
  幽灵: { 超能力: 2, 幽灵: 2, 一般: 0, 恶: 0.5 },
  龙: { 龙: 2, 钢: 0.5, 妖精: 0 },
  恶: { 超能力: 2, 幽灵: 2, 格斗: 0.5, 恶: 0.5, 妖精: 0.5 },
  钢: { 冰: 2, 岩石: 2, 妖精: 2, 火: 0.5, 水: 0.5, 电: 0.5, 钢: 0.5 },
  妖精: { 格斗: 2, 龙: 2, 恶: 2, 火: 0.5, 毒: 0.5, 钢: 0.5 }
};

const getTypeColor = (type) => {
  return typeColorMap[type] || '#9e9e9e';
};

const addLogMessage = (message) => {
  battleLog.value.push(message);
  setTimeout(() => {
    const logElement = document.querySelector('.battle-log');
    if (logElement) {
      logElement.scrollTop = logElement.scrollHeight;
    }
  }, 50);
};

const updateCurrentPokemon = () => {
  if (!Array.isArray(props.playerPokemon) || props.playerPokemon.length === 0) {
    addLogMessage('Error: 玩家无宝可梦可用!');
    battleState.value = 'defeat';
    return;
  }
  if (!Array.isArray(props.opponentPokemon) || props.opponentPokemon.length === 0) {
    addLogMessage('Error: 对方无宝可梦可用!');
    battleState.value = 'victory';
    return;
  }

  // Update current player Pokémon
  while (currentPlayerIndex.value < props.playerPokemon.length && props.playerPokemon[currentPlayerIndex.value].currentHp <= 0) {
    currentPlayerIndex.value++;
  }
  if (currentPlayerIndex.value >= props.playerPokemon.length) {
    battleState.value = 'defeat';
    addLogMessage('你所有宝可梦昏迷!');
    addLogMessage('你输了比赛!');
    return;
  }
  currentPlayer.value = { ...props.playerPokemon[currentPlayerIndex.value], currentHp: props.playerPokemon[currentPlayerIndex.value].currentHp ?? props.playerPokemon[currentPlayerIndex.value].hp };

  // Update current opponent Pokémon
  while (currentOpponentIndex.value < props.opponentPokemon.length && props.opponentPokemon[currentOpponentIndex.value].currentHp <= 0) {
    currentOpponentIndex.value++;
  }
  if (currentOpponentIndex.value >= props.opponentPokemon.length) {
    battleState.value = 'victory';
    addLogMessage('对方所有宝可梦昏迷!');
    addLogMessage('你赢下比赛!');
    return;
  }
  currentOpponent.value = { ...props.opponentPokemon[currentOpponentIndex.value], currentHp: props.opponentPokemon[currentOpponentIndex.value].currentHp ?? props.opponentPokemon[currentOpponentIndex.value].hp };
};

const calculateTypeEffectiveness = (moveType, defenderTypes) => {
  let multiplier = 1;
  const types = defenderTypes.split('/');
  for (const type of types) {
    if (typeChart[moveType] && typeChart[moveType][type]) {
      multiplier *= typeChart[moveType][type];
    }
  }
  return multiplier;
};

const calculateDamage = (attacker, defender, move) => {
  if (!move.power || move.category === 'status') return 0; // Status moves deal no damage

  const level = attacker.level || 50;
  const power = move.power || 40;
  const isSpecial = move.category === 'special';
  const attackStat = isSpecial ? attacker.specialAttack || attacker.attack || 50 : attacker.attack || 50;
  const defenseStat = isSpecial ? defender.specialDefense || defender.defense || 50 : defender.defense || 50;

  // Base damage
  let damage = ((2 * level / 5 + 2) * power * (attackStat / defenseStat) / 50) + 2;

  // Type effectiveness
  const typeEffectiveness = calculateTypeEffectiveness(move.type, defender.type);
  damage *= typeEffectiveness;

  // STAB
  const attackerTypes = attacker.type.split('/');
  if (attackerTypes.includes(move.type)) {
    damage *= 1.5;
  }

  // Critical hit (6.25% chance)
  const isCritical = Math.random() < 0.0625;
  if (isCritical) {
    damage *= 1.5;
  }

  // Random factor (0.85–1.0)
  const randomFactor = Math.random() * (1.0 - 0.85) + 0.85;
  damage *= randomFactor;

  // Floor the damage
  damage = Math.floor(damage);

  return { damage, isCritical, typeEffectiveness };
};

const handleAttack = (moveIndex) => {
  if (turn.value !== 'player' || battleState.value !== 'active' || !currentPlayer.value || !currentOpponent.value || isTurnTransitioning.value || isActionLocked.value) return;

  isActionLocked.value = true; // Lock actions
  const move = currentPlayer.value.moves[moveIndex];
  if (move.pp <= 0) {
    isActionLocked.value = false; // Unlock if move can't be used
    return;
  }

  // Decrement PP
  move.pp = Math.max(0, move.pp - 1);
  props.playerPokemon[currentPlayerIndex.value].moves[moveIndex].pp = move.pp;

  addLogMessage(`${currentPlayer.value.name} 使用了 ${move.name}!`);

  setTimeout(() => {
    const { damage, isCritical, typeEffectiveness } = calculateDamage(currentPlayer.value, currentOpponent.value, move);

    if (typeEffectiveness === 0) {
      addLogMessage("无效的攻击!");
    } else if (typeEffectiveness > 1) {
      addLogMessage("效果拔群!");
    } else if (typeEffectiveness < 1 && typeEffectiveness > 0) {
      addLogMessage("效果微弱");
    }

    if (isCritical) {
      addLogMessage("会心一击!");
    }

    const newOpponentHp = Math.max(0, currentOpponent.value.currentHp - damage);
    currentOpponent.value.currentHp = newOpponentHp;
    props.opponentPokemon[currentOpponentIndex.value].currentHp = newOpponentHp;

    if (damage > 0) {
      addLogMessage(`收到了 ${damage} 伤害!`);
    }

    if (newOpponentHp <= 0) {
      addLogMessage(`${currentOpponent.value.name} 昏迷!`);
      currentOpponentIndex.value++;
      updateCurrentPokemon();
      if (battleState.value === 'active') {
        triggerOpponentTurn();
      }
      return;
    }

    triggerOpponentTurn();
  }, 1000);
};

const usePokeBall = () => {
  if (turn.value !== 'player' || battleState.value !== 'active' || items.value.pokeBall <= 0 || isTurnTransitioning.value || isActionLocked.value) return;

  isActionLocked.value = true; // Lock actions
  items.value.pokeBall -= 1;
  addLogMessage("You threw a Poké Ball!");

  setTimeout(() => {
    const catchChance = Math.random();
    if (catchChance < 0.3) {
      battleState.value = 'caught';
      addLogMessage(`${currentOpponent.value.name} was caught!`);
      myPokemon.value.push({ ...currentOpponent.value, currentHp: currentOpponent.value.hp });
    } else {
      addLogMessage(`${currentOpponent.value.name} broke free!`);
      triggerOpponentTurn();
    }
  }, 1000);
};

const usePotion = () => {
  if (turn.value !== 'player' || battleState.value !== 'active' || items.value.potion <= 0 || isTurnTransitioning.value || isActionLocked.value) return;

  isActionLocked.value = true; // Lock actions
  items.value.potion -= 1;
  const healAmount = 30;
  const newHp = Math.min(currentPlayer.value.hp, currentPlayer.value.currentHp + healAmount);
  const healed = newHp - currentPlayer.value.currentHp;
  currentPlayer.value.currentHp = newHp;
  props.playerPokemon[currentPlayerIndex.value].currentHp = newHp;

  addLogMessage(`You used a Potion on ${currentPlayer.value.name}!`);
  addLogMessage(`${currentPlayer.value.name} restored ${healed} HP!`);

  triggerOpponentTurn();
};

const switchPokemon = (index) => {
  if (turn.value !== 'player' || battleState.value !== 'active' || props.playerPokemon[index].currentHp <= 0 || isTurnTransitioning.value || isActionLocked.value) return;

  isActionLocked.value = true; // Lock actions
  addLogMessage(`${currentPlayer.value.name}, come back!`);
  currentPlayerIndex.value = index;
  updateCurrentPokemon();
  addLogMessage(`Go, ${currentPlayer.value.name}!`);

  triggerOpponentTurn();
};

const triggerOpponentTurn = () => {
  if (battleState.value !== 'active') return;

  isTurnTransitioning.value = true;
  turn.value = 'opponent';
  controlState.value = 'main';

  setTimeout(() => {
    const validMoves = currentOpponent.value.moves.filter(move => move.pp > 0);
    if (validMoves.length === 0) {
      addLogMessage(`${currentOpponent.value.name} has no moves left!`);
      triggerPlayerTurn();
      return;
    }
    const opponentMove = validMoves[Math.floor(Math.random() * validMoves.length)];
    const moveIndex = currentOpponent.value.moves.indexOf(opponentMove);

    // Decrement PP
    opponentMove.pp = Math.max(0, opponentMove.pp - 1);
    props.opponentPokemon[currentOpponentIndex.value].moves[moveIndex].pp = opponentMove.pp;

    addLogMessage(`${currentOpponent.value.name} used ${opponentMove.name}!`);

    setTimeout(() => {
      const { damage, isCritical, typeEffectiveness } = calculateDamage(currentOpponent.value, currentPlayer.value, opponentMove);

      if (typeEffectiveness === 0) {
        addLogMessage("It had no effect!");
      } else if (typeEffectiveness > 1) {
        addLogMessage("It's super effective!");
      } else if (typeEffectiveness < 1 && typeEffectiveness > 0) {
        addLogMessage("It's not very effective...");
      }

      if (isCritical) {
        addLogMessage("A critical hit!");
      }

      const newPlayerHp = Math.max(0, currentPlayer.value.currentHp - damage);
      currentPlayer.value.currentHp = newPlayerHp;
      props.playerPokemon[currentPlayerIndex.value].currentHp = newPlayerHp;

      if (damage > 0) {
        addLogMessage(`It dealt ${damage} damage!`);
      }

      if (newPlayerHp <= 0) {
        addLogMessage(`${currentPlayer.value.name} fainted!`);
        currentPlayerIndex.value++;
        updateCurrentPokemon();
        if (battleState.value === 'active') {
          isTurnTransitioning.value = false;
          triggerPlayerTurn();
        }
        return;
      }

      isTurnTransitioning.value = false;
      triggerPlayerTurn();
    }, 1000);
  }, 1500);
};

const triggerPlayerTurn = () => {
  if (battleState.value !== 'active') return;

  isTurnTransitioning.value = true;

  setTimeout(() => {
    turn.value = 'player';
    isActionLocked.value = false; // Unlock actions for new turn
    addLogMessage("Your turn!");
    isTurnTransitioning.value = false;
  }, 500); // Delay to allow animations to complete
};

const runAway = () => {
  if (turn.value !== 'player' || battleState.value !== 'active' || isTurnTransitioning.value || isActionLocked.value) return;
  isActionLocked.value = true; // Lock actions
  if (confirm("Are you sure you want to run away?")) {
    endBattle();
  } else {
    isActionLocked.value = false; // Unlock if cancelled
  }
};

const endBattle = () => {
  // Sync currentHp back to playerPokemon
  props.playerPokemon.forEach((pokemon, index) => {
    pokemon.currentHp = index === currentPlayerIndex.value ? currentPlayer.value.currentHp : pokemon.currentHp;
  });
  emit('battleEnd');
};

// Watch props to update isBattleReady
watch(() => [props.playerPokemon, props.opponentPokemon], ([player, opponent]) => {
  console.log('Battle props updated:', { player, opponent });
  isBattleReady.value = Array.isArray(player) && player.length > 0 && Array.isArray(opponent) && opponent.length > 0;
  if (isBattleReady.value) {
    // Initialize PP and currentHp if not set
    player.forEach(p => {
      p.moves.forEach(m => {
        if (!m.maxPp) m.maxPp = m.pp || 25;
        if (m.pp === undefined) m.pp = m.maxPp;
        if (!m.power) m.power = 40;
        if (!m.category) m.category = 'physical';
      });
      if (p.currentHp === undefined) p.currentHp = p.hp;
    });
    opponent.forEach(p => {
      p.moves.forEach(m => {
        if (!m.maxPp) m.maxPp = m.pp || 25;
        if (m.pp === undefined) m.pp = m.maxPp;
        if (!m.power) m.power = 40;
        if (!m.category) m.category = 'physical';
      });
      if (p.currentHp === undefined) p.currentHp = p.hp;
    });
    currentPlayerIndex.value = 0;
    currentOpponentIndex.value = 0;
    updateCurrentPokemon();
    addLogMessage("战斗开始!");
    addLogMessage(`去吧, ${player[0].name}!`);
    addLogMessage(`对手派出了 ${opponent[0].name}!`);
    addLogMessage("你的回合!");
  }
}, { immediate: true });

onMounted(() => {
  console.log('Battle mounted with props:', { playerPokemon: props.playerPokemon, opponentPokemon: props.opponentPokemon });
  nextTick(() => {
    if (Array.isArray(props.playerPokemon) && props.playerPokemon.length > 0 && Array.isArray(props.opponentPokemon) && props.opponentPokemon.length > 0) {
      isBattleReady.value = true;
      currentPlayerIndex.value = 0;
      currentOpponentIndex.value = 0;
      updateCurrentPokemon();
    } else {
      addLogMessage("Error: Pokémon data missing!");
    }
  });
});
</script>

<style scoped>
.battle {
  display: flex;
  flex-direction: column;
}

.battle-arena {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.opponent-area {
  background: linear-gradient(to bottom, #f0f0f0, #e0e0e0);
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pokemon-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pokemon-name {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 8px;
}

.hp-bar-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.hp-bar-container.reverse {
  flex-direction: row-reverse;
}

.hp-bar {
  width: 128px;
  height: 8px;
  background-color: #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.hp-fill {
  height: 100%;
  background-color: #4CAF50;
  transition: width 0.5s;
}

.hp-fill.low-hp {
  background-color: #f44336;
}

.hp-text {
  font-size: 14px;
}

.pokemon-sprite-container {
  position: relative;
}

.sprite-shadow {
  position: absolute;
  bottom: 0;
  width: 64px;
  height: 64px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  z-index: -1;
}

.pokemon-sprite {
  width: 96px;
  height: 96px;
  transform: scale(1.5);
}

.battle-log-container {
  flex: 1;
  background-color: rgba(255, 255, 255, 0.8);
  overflow-y: auto;
  max-height: 160px;
}

.battle-log {
  background-color: white;
  border-radius: 8px;
  padding: 12px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
  height: 100%;
  overflow-y: auto;
}

.log-entry {
  font-size: 14px;
  margin-bottom: 4px;
}

.player-area {
  background: linear-gradient(to top, #f0f0f0, #e0e0e0);
  padding: 16px;
}

.player-stats {
  text-align: right;
}

.battle-controls {
  background-color: #333;
  padding: 16px;
  flex: 1;
}

.controls-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.main-controls-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.control-button {
  padding: 12px;
  font-size: 16px;
  border-radius: 8px;
  color: white;
  text-align: center;
  transition: transform 0.1s, box-shadow 0.1s;
}

.control-button:hover:not(.disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.control-button:active:not(.disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.control-button.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.fight-button {
  background-color: #e74c3c;
}

.fight-button:hover:not(.disabled) {
  background-color: #c0392b;
}

.item-button {
  background-color: #f39c12;
}

.item-button:hover:not(.disabled) {
  background-color: #d35400;
}

.switch-button {
  background-color: #2ecc71;
}

.switch-button:hover:not(.disabled) {
  background-color: #27ae60;
}

.run-button {
  background-color: #3498db;
}

.run-button:hover:not(.disabled) {
  background-color: #2980b9;
}

.moves-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.move-button {
  padding: 12px;
  font-size: 16px;
  border: 2px solid #333;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  text-align: center;
  position: relative;
  transition: transform 0.1s, box-shadow 0.1s;
}

.move-button:hover:not(.disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.move-button:active:not(.disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.move-button.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.move-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.move-name {
  font-weight: bold;
  font-size: 16px;
}

.type-badge {
  position: absolute;
  top: 4px;
  right: 4px;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  color: white;
  background-color: #000;
}

.pp-text {
  position: absolute;
  bottom: 4px;
  right: 4px;
  font-size: 12px;
  color: #333;
}

.items-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.item-button {
  padding: 12px;
  font-size: 16px;
  border-radius: 8px;
  background-color: #f39c12;
  color: white;
  text-align: center;
  transition: transform 0.1s, box-shadow 0.1s;
}

.item-button:hover:not(.disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.item-button:active:not(.disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.item-button.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pokemon-switch-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}

.pokemon-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.2s;
}

.pokemon-card:not(.disabled) {
  cursor: pointer;
}

.pokemon-card:hover:not(.disabled) {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.pokemon-card.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pokemon-card-content {
  padding: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pokemon-thumbnail {
  width: 64px;
  height: 64px;
}

.pokemon-card-name {
  font-weight: 500;
  text-align: center;
  font-size: 14px;
  margin: 4px 0;
}

.pokemon-level {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.back-button {
  background-color: #3498db;
  color: white;
  padding: 12px;
  border-radius: 8px;
  margin-top: 8px;
}

.back-button:hover:not(.disabled) {
  background-color: #2980b9;
}

.back-button.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.battle-result {
  text-align: center;
}

.result-text {
  color: white;
  font-size: 20px;
  margin-bottom: 16px;
}

.return-button {
  background-color: #3498db;
  color: white;
  padding: 12px 32px;
  font-size: 16px;
  border-radius: 8px;
}

.return-button:hover {
  background-color: #2980b9;
}

.loading {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 18px;
}
</style>